﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class UsersByGPSStocks : ClassManager.SessionManagerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SessionManager objSessionManager = new SessionManager();
                objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

                HttpContext.Current.Session["CompanyID"] = objSessionManager.CompanyIDSelectedComboBox;

                if (!Page.IsPostBack)
                {
                    GridSortExpression expression = new GridSortExpression();
                    expression.FieldName = "GPSGroupIdSource.Name";
                    expression.SetSortOrder("Ascending");
                    this.GPSGroupsGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                    expression = new GridSortExpression();
                    expression.FieldName = "Name";
                    expression.SetSortOrder("Ascending");
                    this.UsersSelectedGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                    expression = new GridSortExpression();
                    expression.FieldName = "Name";
                    expression.SetSortOrder("Ascending");
                    this.GPSStocksGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
                }
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo cargar la session del usuario");
            }
        }

        protected void showMessage(string msg)
        {
            RadWindowManager1.RadAlert("<center>" + msg + "</center>", 400, 100, "Grupo de dispositivos", null, null);
        }

        protected void UsersSelectedGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetAllUsersByCompany(getSessionManager().CompanyIDSelectedComboBox);
            ResizeGrid();
        }

        private void GetAllUsersByCompany(int companyId)
        {
            try
            {
                UsersSelectedGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.UsersProvider.GetByCompanyID(companyId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GetUsersByCompanyIDByGPSGorupID(int companyID, int gpsGroupID)
        {
            UsersSelectedGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.UsersProvider.GetByCompanyIDByGPSGroupID(companyID, getGPSGroupIDSelected());
        }

        

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        /*protected void UsersSelectedGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Data.DataRepository.UsersByGpsGroupsProvider.Delete(tm, Entity["Username"].ToString(), getSessionManager().CompanyIDSelectedComboBox, getGPSGroupIDSelected());
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo eliminar el usuario del grupo");
            }
        }*/



        protected void GPSGroupsGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            getGPSGroups();
            ResizeGrid();
        }

        private void ResizeGrid()
        { 
            decimal Height = Convert.ToDecimal(HiddenFieldHeight.Value) / 2;

            UsersSelectedGrid.Height = Unit.Parse(Convert.ToString(Height));
            GPSGroupsGrid.Height = Unit.Parse(Convert.ToString(Height));
            GPSStocksGrid.Height = Unit.Parse(Convert.ToString(Height));
        }

        protected void GPSGroupsGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            setSessionManager(getGPSGroupIDSelected(), getUsernameSelected());

            getGPSStocksByUsersAndGPSGroups();
            GPSStocksGrid.DataBind();
            ResizeGrid();
        }

        protected void setSessionManager(int gpsGroupID, string username)
        {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
            objSessionManager.UsersByGPSStock_GPSStockComboSearch_GPSGroupID = gpsGroupID;
            objSessionManager.UsersByGPSStock_GPSStockComboSearch_username = username;
            HttpContext.Current.Session["SessionManager"] = objSessionManager;
        }


        protected int getGPSGroupIDSelected()
        {

            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in GPSGroupsGrid.SelectedItems)
                {
                    return int.Parse(selectedItem["GPSGroupId"].Text);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return -1;
        }

        protected string getUsernameSelected()
        {

            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in UsersSelectedGrid.SelectedItems)
                {
                    return selectedItem["Username"].Text;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return "";
        }

        private GPSTrackingDBV2.Entities.GpsGroups Invoke_Entity(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.GpsGroups GpsGroupsEntity = new GPSTrackingDBV2.Entities.GpsGroups();
            GpsGroupsEntity.GpsGroupId = Convert.ToInt32(Entity[GPSTrackingDBV2.Entities.GpsGroupsColumn.GpsGroupId.ToString()]);
            GpsGroupsEntity.Name = Entity[GPSTrackingDBV2.Entities.GpsGroupsColumn.Name].ToString();

            return GpsGroupsEntity;
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            GPSGroupsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in GPSGroupsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }

            clearGPSStocksGrid();
            GPSGroupsGrid.MasterTableView.Rebind();
            ResizeGrid();
        }

        protected void lbClearFilters2_Click(object sender, EventArgs e)
        {
            UsersSelectedGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in UsersSelectedGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            clearGPSGroupGrid();
            clearGPSStocksGrid();
            UsersSelectedGrid.MasterTableView.Rebind();
        }


        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_miniError", "objWindowsMessageManager.show_miniError('" + msg + "','Usuario por grupos de dispositivos ...');", true);
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        private void clearGPSGroupGrid()
        {
            GPSGroupsGrid.DataSource = new string[] { };
            GPSGroupsGrid.DataBind();
            ResizeGrid();
        }

        private void clearGPSStocksGrid()
        {
            GPSStocksGrid.DataSource = new string[] { };
            GPSStocksGrid.DataBind();
            ResizeGrid();
        }

        protected void UsersSelectedGrid_SelectedIndexChanged(object sender, EventArgs e)
        {

            getGPSGroups();
            GPSGroupsGrid.DataBind();
            ResizeGrid();
        }

        protected void getGPSGroups() {
            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.UsersByGpsGroups> UsersByGpsGroupsEntity = GPSTrackingDBV2.Data.DataRepository.UsersByGpsGroupsProvider.GetByUsernameCompanyId(getUsernameSelected(), getSessionManager().CompanyIDSelectedComboBox);
            GPSTrackingDBV2.Data.DataRepository.UsersByGpsGroupsProvider.DeepLoad(UsersByGpsGroupsEntity, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.GpsGroups));
            GPSGroupsGrid.DataSource = UsersByGpsGroupsEntity;
        }

        protected void GPSStocksGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            getGPSStocksByUsersAndGPSGroups();
            ResizeGrid();
        }

        protected void getGPSStocksByUsersAndGPSGroups()
        {
            GPSStocksGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.GPSStockProvider.GetAllByUsernameAndGPSGroupID(getSessionManager().CompanyIDSelectedComboBox, getUsernameSelected(), getGPSGroupIDSelected());
        }

        protected void uscGPSSearchCombo_OnAcceptEvent(List<GridDataItem> rows)
        {

            int GPSGroupID = getGPSGroupIDSelected();

            if (GPSGroupID == -1 && rows.Count > 0)
            {
                showErrorMessage("Debe seleccionar un usuario para asociar los dispositivos.");
            }
            else
            {

                foreach (GridDataItem row in rows)
                {
                    GPSTrackingDBV2.Entities.UsersByGpsStocks UsersByGpsStocksEntity = new GPSTrackingDBV2.Entities.UsersByGpsStocks();

                    UsersByGpsStocksEntity.Dispose();
                    UsersByGpsStocksEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;
                    UsersByGpsStocksEntity.Username = getUsernameSelected();
                    UsersByGpsStocksEntity.GpsImei = row.Cells[3].Text;

                    GPSTrackingDBV2.Data.DataRepository.UsersByGpsStocksProvider.Insert(UsersByGpsStocksEntity);
                }
                getGPSStocksByUsersAndGPSGroups();
                GPSStocksGrid.DataBind();
            }
            ResizeGrid();
        }

        protected void uscGPSSearchCombo_OnCancelEvent()
        {
            ResizeGrid();
        }

        protected void GPSStocksGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Data.DataRepository.UsersByGpsStocksProvider.Delete(tm, getUsernameSelected(), getSessionManager().CompanyIDSelectedComboBox, Entity["GPSImei"].ToString());
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo eliminar el gps del usuario");
            }
        }

        protected void lbClearFilters3_Click(object sender, EventArgs e)
        {
            GPSStocksGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in GPSStocksGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }

            GPSStocksGrid.MasterTableView.Rebind();
        }

        protected void lbShowError3_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        /*

        protected void uscUsersByCompanyIDSearch_OnCancelEvent()
        {
            ResizeGrid();
        }

        protected void uscUsersByCompanyIDSearch_OnAcceptEvent(List<GridDataItem> rows)
        {


            int gpsGroupID = getGPSGroupIDSelected();
            int companyID = getSessionManager().CompanyIDSelectedComboBox;

            if (gpsGroupID == -1 && rows.Count > 0)
            {
                showErrorMessage("Debe seleccionar un grupo para asociar los usuarios.");
            }
            else
            {
                foreach (GridDataItem row in rows)
                {

                    GPSTrackingDBV2.Entities.UsersByGpsGroups UsersByGpsGroupsEntity = new GPSTrackingDBV2.Entities.UsersByGpsGroups();
                    UsersByGpsGroupsEntity.Dispose();
                    UsersByGpsGroupsEntity.GpsGroupId = gpsGroupID;
                    UsersByGpsGroupsEntity.Username = row.Cells[3].Text;
                    UsersByGpsGroupsEntity.CompanyId = companyID;
                    try
                    {
                        GPSTrackingDBV2.Data.DataRepository.UsersByGpsGroupsProvider.Insert(UsersByGpsGroupsEntity);
                    }
                    catch { }
                }
                GetUsersByCompanyIDByGPSGorupID(companyID, gpsGroupID);
                UsersSelectedGrid.DataBind();
            }
            ResizeGrid();
        }*/
    }
}